package com.paul.sys.tools;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by yangjianbo on 2016/2/17.
 */
public class PrimaryGenerater {
    private  final String SERIAL_NUMBER = "XXXX"; // 流水号格式
    private static PrimaryGenerater primaryGenerater = null;
    private  int key=0;       //唯一机器码
    private String sno=null;
    private PrimaryGenerater() {
    }

    /**
     * 取得PrimaryGenerater的单例实现
     *
     * @return
     */
    public static PrimaryGenerater getInstance() {
        if (primaryGenerater == null) {
            synchronized (PrimaryGenerater.class) {
                if (primaryGenerater == null) {
                    primaryGenerater = new PrimaryGenerater();
                    Random random = new Random();
                    primaryGenerater.key=random.nextInt(9000)+1000;
                }
            }
        }
        return primaryGenerater;
    }

    /**
     * 生成下一个编号
     */
    public synchronized String generaterNextNumber() {
        String id = null;
        Date date = new Date();
        int count = SERIAL_NUMBER.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append("0");
        }
        DecimalFormat df = new DecimalFormat(sb.toString());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        if (sno == null) {
            id = formatter.format(date) + sb.toString();
            id=key+id;
        } else {
            id = formatter.format(date)
                    + df.format(1 + Integer.parseInt(sno.substring(8, 12)));
        }
        return id;
    }
}
